package com.qf.fcy.youshare.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

/**
 * Created with IntelliJ IDEA.
 * User: Alex[FR]
 * Date: 2015/2/6
 * Email: alex_fcy@163.com
 */

/**
 * 通用的图片下载异步任务，通过构造方法设置，需要接受图片的ImageView
 */
public class ImageLoader extends AsyncTask<String, Integer, byte[]> {
    // 图片请求地址
    private String reqImgUrl;
    private ImageView myImageView;

    public ImageLoader(ImageView myImageView) {
        this.myImageView = myImageView;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        byte[] ret = null;

        if (params != null && params.length > 0) {
            reqImgUrl = params[0];

            //TODO 下载 imgURL 图片
            ret = HttpClientHelper.get(reqImgUrl);
        }
        return ret;
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        if (bytes != null) {
            FileCache fileCache = FileCache.getInstance();
            fileCache.putContent(reqImgUrl,bytes);

            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            // TODO 更新内容缓存
            ImageCache imageCache = ImageCache.getInstance();
            // 向内存中设置图片
            imageCache.putImage(reqImgUrl, bitmap);

            String tarImgUrl = (String) myImageView.getTag();
            // 检查请求地址与实际地址是否相等
            if (tarImgUrl != null) {
                if (reqImgUrl.equals(tarImgUrl)) {
                    myImageView.setImageBitmap(bitmap);
                }
            }

            // 使用完Bitmap释放资源
            // 判断Bitmap是否被回收
            if (bitmap != null && bitmap.isRecycled()) {
                bitmap.recycle();
                bitmap = null;
            }
            System.gc();
        }
    }
}
